<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        .box{
            width: 500px;
            margin: 50px auto;
            border: 1px solid blue;
        }

    </style>
</head>
<body>
    <div class="box">
       <canvas id="msk" width='500' height='400'></canvas>
    </div>
    <script>
        let msk=document.getElementById('msk')
        let ctx=msk.getContext('2d')
        //本地图片会认定为跨域
        // let img=new Image()
        // img.src='img/1.jpg'
        // let imgdata
        // img.onload=function(){
        //     ctx.save()
        //     ctx.drawImage(img,0,0,msk.width/2,msk.height)
        //     imgdata=ctx.getImageData(0,0,msk.width/2,msk.height)
        //     console.log(getPx(imgdata,2,5),'222',imgdata)
        //     ctx.restore()
        // }
        ctx.save()
        let linger=ctx.createLinearGradient(0,0,msk.width/2,msk.height)
        linger.addColorStop(0.1,'red')
        linger.addColorStop(0.5,'green')
        linger.addColorStop(0.6,'blue')
        linger.addColorStop(1.0,'yellow')
        ctx.fillStyle=linger
        ctx.fillRect(0,0,msk.width/2,msk.height)
        ctx.restore()
         
        let oldimg=ctx.getImageData(0,0,msk.width,msk.height)
        let newimg=ctx.createImageData(msk.width/2,msk.height)
        let size=3
        let w=msk.width
        for(let i=0;i<msk.width/size/2;i++){
            for( let j=0;j<msk.height;j++){
                let color=getPx(oldimg,Math.floor(Math.random()*size)+i*size,Math.floor(Math.random()*size)+j*size)

                for(let a=0;a<size;a++){
                    for(let b=0;b<size;b++){
                        setPx(newimg,i*size+a,j*size+b,color)
                    }
                }

            }
        }
        ctx.putImageData(newimg,msk.width/2,0)


        function getPx(imgdata,x,y){
            let color=[]

            color[0]=imgdata.data[4*(y*w+x)]
            color[1]=imgdata.data[4*(y*w+x)+1]
            color[2]=imgdata.data[4*(y*w+x)+2]
            color[3]=imgdata.data[4*(y*w+x)+3]
            return color
        }
        
        function setPx(img,x,y,color){
            img.data[4*(y*w+x)]=color[0]
            img.data[4*(y*w+x)+1]=color[1]
            img.data[4*(y*w+x)+2]=color[2]
            img.data[4*(y*w+x)+3]=color[3]
        }
    </script>
</body>
</html>